<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        class="mr-5px"
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['config:drawing-component:save']"
        >保 存</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        style="display: flex"
        class="mt-10px mb-10px"
      >
        <el-form-item label="产品类型" prop="productType">
          <el-input
            style="width: 200px"
            v-model="formData.productType"
            placeholder="请输入产品类型"
          />
        </el-form-item>
        <el-form-item label="状态" prop="dictEnableStatus">
          <el-select v-model="formData.dictEnableStatus" placeholder="请选择状态">
            <el-option
              v-for="dict in getIntDictOptions('dict_enable_status')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button class="mt-5px mb-5px" type="primary" @click="addCol">新增行</el-button>
      <el-table
        ref="singleTableRef"
        :data="formData.products"
        style="width: 100%"
        border
        class="tableView"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="partType" label="部件类型" min-width="200" align="left">
          <template #default="scope">
            <el-input
              v-nextInput="'partType'"
              name="partType"
              v-model="scope.row.partType"
              class="tableIpt"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="left">
          <template #default="scope">
            <el-button size="small" type="danger" link @click="delTableCol(scope.$index)"
              >移除行</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as DrawingComponentApi from '@/api/config/drawingComponent'
import { useTagsViewStore } from '@/store/modules/tagsView'

const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  productType: undefined,
  dictEnableStatus: undefined,
  products: []
})
const formRules = reactive({
  productType: [{ required: true, message: '产品类型不能为空', trigger: 'blur' }],
  dictEnableStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 提交表单 */
const { t } = useI18n() // 国际化
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DrawingComponentApi.DrawingComponentVO
    data.products = data.products.filter((item) => item.partType != '')
    if (query.type === 'create') {
      await DrawingComponentApi.createDrawingComponent(data)
      message.success(t('common.createSuccess'))
    } else {
      await DrawingComponentApi.updateDrawingComponent(data)
      message.success(t('common.updateSuccess'))
    }
    goBack()
  } finally {
    formLoading.value = false
  }
}

/** 重置数据 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    productType: undefined,
    dictEnableStatus: undefined,
    products: []
  }
  formRef.value?.resetFields()
}

/**新增行 */
const addCol = () => {
  console.log('addCol')
  formData.value.products.push({
    partType: ''
  })
}

/**移除行 */
const delTableCol = (index: number) => {
  formData.value.products.splice(index, 1)
}

/**返回 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path: '/config/config/cartographicManagement/configCenter/drawingComponent'
  })
}

// 获得id
const { query } = useRoute() // 路由的查
const contentHeight = ref(0)
/** 初始化 */
onMounted(async () => {
  formLoading.value = true
  await resetForm()
  if (query.id) {
    formData.value = await DrawingComponentApi.getDrawingComponent(query.id)
  }
  contentHeight.value = document.body.clientHeight - 127
  formLoading.value = false
})
</script>
<style lang="scss" scoped>
.contentView {
  padding: 10px;
  background: #fff;
}
.routeHeader {
  width: 100%;
  border-bottom: 1px solid #969696;
  display: flex;
  align-items: center;
  padding: 10px 0;
}
.tableIpt {
  :deep(.el-input__inner) {
    text-align: left;
  }
}
.tableView {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
    cursor: default;
    .el-input__inner {
      cursor: default !important;
    }
  }
}
</style>
